
package com.gxa.meiye.admin.platform.filter;

import com.gxa.meiye.admin.platform.pojo.domain.JwtToken;
import com.gxa.meiye.admin.platform.pojo.vo.AdminVo;
import com.gxa.meiye.admin.platform.service.AdminService;
import com.gxa.meiye.admin.platform.utils.JwtUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;


@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Autowired
    private AdminService adminService;

//    @Override
//    public boolean supports(AuthenticationToken token) {
//        return token instanceof OAuth2Token;
//    }

    @Override
    public boolean supports(AuthenticationToken token) {
        // 定义该Realm可以处理哪个类型的token
        return token instanceof OAuth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("********************doGetAuthorizationInfo*******************************");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        String name = principalCollection.toString();
        String username = JwtUtil.getUsername(name);
        System.out.println(name);
        Set<String> perms = adminService.queryPerms(username);
        simpleAuthorizationInfo.setStringPermissions(perms);
        System.out.println(perms);
        return simpleAuthorizationInfo;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("===========doGetAuthenticationInfo==========================");
        //根据收到的token 解密 进行判断是否正确，正确就取出用户id，将用户对象查出来。
        String accessToken = (String) token.getPrincipal();
        String credentials = (String) token.getCredentials();
        String account = JwtUtil.getUsername(accessToken);
//        String account = token1.getUsername();
        AdminVo adminVo = adminService.queryAdminByName(account);
        System.out.println(adminVo.getPwd());
        System.out.println("=====================================================================");
//        ByteSource salt = ByteSource.Util.bytes(user.getSalt());
//        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(token.getPrincipal(),adminVo.getPwd(),getName());
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), getName());
        System.out.println("=====================================================================");
        return simpleAuthenticationInfo;

    }
}
